package com.chidopi.market.bookstore.actions;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chidopi.cdf.exception.CdfException;
import com.chidopi.cdf.service.IBaseService;
import com.chidopi.cdf.struts1actions.CdfDispatchAction;
import com.chidopi.cdf.util.ModelContextFactory;
import com.chidopi.market.bookstore.domain.BookItems;
import com.chidopi.market.bookstore.domain.ProductID2Book;
import com.chidopi.market.bookstore.domain.Subscribe4iOS;
import com.chidopi.market.util.MessageHandler;

public class ProductID2BookAction extends CdfDispatchAction{
	
	private static Logger logger = LoggerFactory.getLogger(ProductID2BookAction.class);
	
	private IBaseService<ProductID2Book> baseService;
	
	private IBaseService<BookItems> bookService;
	
	private IBaseService<Subscribe4iOS> iosService;
	
	public ProductID2BookAction(){
		this("");
	}
	
	@SuppressWarnings("unchecked")
	public ProductID2BookAction(String entryURL) {
		this.entryURL = entryURL;
		try {
			this.baseService = (IBaseService<ProductID2Book>)
				ModelContextFactory.get("productID2BookService", IBaseService.class);			
			bookService = (IBaseService<BookItems>)
				ModelContextFactory.get("bookItemsService", IBaseService.class);
			iosService = (IBaseService<Subscribe4iOS>)
				ModelContextFactory.get("subscribe4iOSService", IBaseService.class);
		} catch (Exception e) {
			this.baseService = null;
			logger.warn("initial", e);
		}
	}
	
	public ActionForward init(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("vo", null);
		dynaForm.set("op", null);		
		return mapping.findForward("success");
	}
	
	public ActionForward back(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("success");
	}
	
	private static final String[] conditions = {"product_id", "product_type"};
	public ActionForward query(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (null == this.baseService) return mapping.findForward("error");
		StringBuffer sql = new StringBuffer();
		ArrayList<String> args = new ArrayList<String>();
		for (String cond : conditions) {
			String value = (String) request.getParameter(cond);
			if (value == null || value.trim().equals("")) continue;
			logger.debug(cond + "=" + value);
			
			if (sql.length() > 1) sql.append("and ");
			
			if(cond.equals("product_id")){
				sql.append("a.product_id like ?");
				args.add("%" + value +"%");
			}else{
				sql.append("a." + cond +" = ? ");
				args.add(value);
			}		
		}
		logger.debug("sql=" + sql.toString());
		List<ProductID2Book> list = this.baseService.find(sql.toString(),args.toArray());
		logger.debug("size=" + list.size());
		JSONArray json = JSONArray.fromObject(list);
		
		PrintWriter out=response.getWriter();
		logger.debug(json.toString());
        out.println(json);
        out.flush();
		return null;
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("product_id");
		logger.debug("product_id = " + id);
		ProductID2Book t = this.baseService.findById(id);
		if (null == t) {
			logger.warn("ProductID2Book[product_id={}] is deleted!!", id);
			return mapping.findForward("err");
		}
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "delete");
		dynaForm.set("vo", t);
		int type = t.getProduct_type();
		if(type == 1){
			List<BookItems> books = this.bookService.find(" enable_flag = 'Y' ");
		    dynaForm.set("books", books);
		}else{
			List<Subscribe4iOS> books = this.iosService.find(null);
			dynaForm.set("books",books);
		}
		return mapping.findForward("success");
	}

	public ActionForward insert(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("product_id");
		logger.debug("product_id = " + id);
		ProductID2Book t = this.baseService.findById(id);
		if (null == t) t = new ProductID2Book();
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "insert");
		dynaForm.set("vo", t);
		Integer type = t.getProduct_type();
		if(type != null){
			if(type == 1){
				List<BookItems> books = this.bookService.find(" enable_flag = 'Y' ");
			    dynaForm.set("books", books);
			}else if(type==2){
				List<Subscribe4iOS> books = this.iosService.find(null);
				dynaForm.set("books",books);
			}
		}
		return mapping.findForward("success");
	}

	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("product_id");
		logger.debug("product_id = " + id);
		ProductID2Book t = this.baseService.findById(id);
		if (null == t) {
			logger.warn("ProductID2Book[product_id={}] is deleted!!", id);
			return mapping.findForward("err");
		}
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "update");
		dynaForm.set("vo", t);
		int type = t.getProduct_type();
		if(type == 1){
			List<BookItems> books = this.bookService.find(" enable_flag = 'Y' ");
		    dynaForm.set("books", books);
		}else{
			List<Subscribe4iOS> books = this.iosService.find(null);
			dynaForm.set("books",books);
		}
		return mapping.findForward("success");
	}

	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String op = request.getParameter("op");
		logger.debug("op=" + op);
		ProductID2Book t = new ProductID2Book();
		try {
			DynaBean dynaForm = (DynaBean) form;
			PropertyUtils.copyProperties(t, dynaForm.get("vo"));
			logger.debug(t.getProduct_id() + ":" + t.getProduct_type() + "/" + t.getBook_id());
		} catch (Exception e) {
			logger.warn("PropertyUtils", e);
			return mapping.findForward("err");
		}

		int ret = -1;
		if ("insert".equals(op)) {			
			ret = this.baseService.insert(t);
		} else if ("update".equals(op)) {
			ret = this.baseService.update(t);
		} else if ("delete".equals(op)) {
			try{
				ret = this.baseService.delete(t);
			}catch(CdfException cex){
				MessageHandler.getInstance().processError(request, cex.getMessage());
			}			
		}
		if (ret > -1) {
			request.setAttribute("entryURL", entryURL);
			return mapping.findForward("success");
		}else {
			return mapping.findForward("err");
		}
	}
	
	public ActionForward ajaxValidateProductId(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String product_id = request.getParameter("product_id");
		
		logger.debug("product_id = " + product_id);
		ProductID2Book product = this.baseService.findById(product_id);
		if (null == product) {
			MessageHandler.getInstance().processAjaxMessage(response,"OK");
		}else{			
			String message = MessageHandler.getInstance().getResourceMessage(request,"error.productid2book.productid.duplicate");
			logger.warn(message);
			MessageHandler.getInstance().processAjaxMessage(response,message);
			
		}
		return null;
	}

	public ActionForward ajaxGetBooks(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		List<BookItems> books = this.bookService.find(null);
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		if(books != null){
			for(BookItems book : books){
				Map<String, String> map = new HashMap<String, String>();
				map.put("id", book.getId().toString());
				map.put("name", book.getBookname());
				list.add(map);
			}
		}
		
		JSONArray json = JSONArray.fromObject(list);		
		PrintWriter out=response.getWriter();
		logger.debug(json.toString());
        out.println(json);
        out.flush();
		
		return null;
	}
	
	public ActionForward ajaxGetSubscriptions(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		List<Subscribe4iOS> subs = this.iosService.find(null);
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		if(subs != null){
			for(Subscribe4iOS ios : subs){
				Map<String, String> map = new HashMap<String, String>();
				map.put("id", ios.getId().toString());
				map.put("name", ios.getId() + ":" +  ios.getSubscribe().getName());
				list.add(map);
			}
		}
		
		JSONArray json = JSONArray.fromObject(list);
		PrintWriter out=response.getWriter();
		logger.debug(json.toString());
        out.println(json);
        out.flush();
		
		return null;
	}
}
